package com.imohoo.libs.converter;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.imohoo.jni.Main;

import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Converter;

final class SpJsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;
    private String cmd;
    private String opt;

    SpJsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapter, String cmd, String opt) {
        this.gson = gson;
        this.adapter = adapter;
        this.cmd = cmd;
        this.opt = opt;
    }

    @Override
    public RequestBody convert(T value) throws IOException {
        // 文件类型封装
        if (value instanceof SpFile) {
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            for (Map.Entry<String, Object> entry : ((SpFile) value).getParams().entrySet()) {
                builder.addFormDataPart(entry.getKey(), String.valueOf(entry.getValue()));
            }

            if (((SpFile) value).getFilespath() != null && ((SpFile) value).getFilespath().size() > 0) {
                for (String key : ((SpFile) value).getFilespath()) {
                    File f = new File(key);
                    // MediaType mediaType = MediaType.parse("video/mp4");
                    builder.addFormDataPart(((SpFile) value).getFiletag(), f.getName(), RequestBody.create(null, f));
                }
            }
            //构建请求体
            return builder.build();
        }
        // cmd opt封装
        if (value instanceof SpRequest) {
            if (!TextUtils.isEmpty(cmd)) {
                ((SpRequest) value).put("cmd", cmd);
            }
            if (!TextUtils.isEmpty(opt)) {
                ((SpRequest) value).put("opt", opt);
            }
        }
        // 请求加密
        return new FormBody.Builder()
                .add("APIDATA", new String(Base64.encodeBase64(Main.abc(gson.toJson(value).getBytes(), Main.ENCRYPT, 1))))
                .add("api_version", "2_7")
                .build();
    }
}
